#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

class Server_UDP
{
public:
    Server_UDP(std::string& IP, uint16_t& port)
    :IP_(IP), port_(port)
    {
        socket_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (socket_ == -1)
        {
            std::cerr << "socket error: " << errno << strerror(errno) << std::endl;
            exit(1);
        }
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(IP_.c_str());
        local.sin_port = htons(port_);
        int n = bind(socket_, (sockaddr*)&local, sizeof(local));
        if (n == -1)
        {
            std::cerr << "bind error: " << errno << ": "<< strerror(errno) << std::endl;
            exit(2);
        }
    }

    void receive(void)
    {
        char buff[1024];
        struct sockaddr_in client_addr;
        socklen_t client_len = sizeof(client_addr);
        while(true)
        {
            ssize_t s = recvfrom(socket_, buff, sizeof(buff), 0, (sockaddr*)&client_addr, &client_len);
            if (s != 0)
            {
                std::cout << "["<< inet_ntoa(client_addr.sin_addr) << "] "<< client_addr.sin_port << " :" <<  buff << std::endl;
            }
        }
    }

    ~Server_UDP()
    {
        close(socket_);
    }

private:
    int socket_;    //socket文件描述符
    std::string IP_;    //本地IP
    uint16_t port_;     //本地端口
};
